<template>
  <div v-loading="loading" class="grade" element-loading-text="加载中...">
    <div class="header flex-justify-between">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="onOpenAddField"> 添加字段 </HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="disableBatchBtn">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(false)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="updateBatchNetworkFieldStatus(true)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="onDelBatchField()">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <!-- 搜索条件 -->
      <div class="search flex-align-center">
        <el-input
          v-model.trim="listFieldSearch.name"
          placeholder="字段名称"
          class="input-width"
          clearable
          @keyup.enter="getList"
          @clear="getList"
        />
        <HButton type="primary" @click="getList">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <!-- 列表表格 -->
    <div class="table-grade">
      <el-table
        ref="tableDom"
        border
        stripe
        resizable
        :data="tableData"
        height="100%"
        style="position: absolute"
        @selection-change="handleChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column show-overflow-tooltip type="index" label="序号" width="55" />
        <el-table-column show-overflow-tooltip prop="name" label="字段名称" width="120" />
        <el-table-column show-overflow-tooltip prop="name" label="字段类型" width="120">
          <template #default="scope">
            <span>
              {{
                scope.row.type == 1
                  ? '文本'
                  : scope.row.type == 2
                  ? '多行文本'
                  : scope.row.type == 3
                  ? '单选'
                  : scope.row.type == 4
                  ? '多选'
                  : scope.row.type == 5
                  ? '多图'
                  : scope.row.type == 6
                  ? '附件'
                  : '视频'
              }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="content" label="字段内容" />
        <el-table-column show-overflow-tooltip prop="tip" label="字段提示" />
        <el-table-column label="移动端显示" width="120">
          <template #default="scope">
            <div style="display: flex; align-items: center; gap: 5px">
              <el-switch v-model="scope.row.mobileShow" disabled />
              <span v-if="scope.row.mibileShow">显示</span>
              <span v-else>隐藏</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status" type="info">禁用</HStatus>
            <HStatus v-else>启用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="required" label="是否必填" width="120">
          <template #default="scope">
            <span>
              {{ scope.row.required == true ? '必填' : '可填' }}
            </span>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="onOpenEditField(scope.row)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页组件 -->
    <div class="footer flex-justify-end">
      <Pagination
        ref="pagingtion"
        :list_total="fieldTotal"
        @size-change="getList"
        @current-change="getList"
      />
    </div>
  </div>
  <!-- 添加/编辑  字段弹窗 -->
  <SelfDefined
    :title="fieldDialogTitle"
    :type="1"
    :is-open="networkEmpFieldDialog"
    :field-vo="networkEmpFieldVo"
    @on-delete="delNetworkEmpFieldApi($event)"
    @on-save="saveApi($event)"
    @on-close="networkEmpFieldDialog = false"
  >
  </SelfDefined>
</template>

<script setup lang="ts">
  import { ref, reactive, markRaw, watch } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { Search, Delete, Warning, ArrowDown, CircleCheck } from '@element-plus/icons-vue'

  // 引入组件工具
  import Pagination from '../../../../../../../components/Pagination/index.vue'
  import {
    getNetworkEmpFieldDetail,
    saveNetworkEmpField,
    getNetworkEmpList,
    batchUpdateNetworkEmpFieldStatus,
    delNetworkEmpField,
  } from '@/api/network'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HLink from '@/components/common/link/HLink.vue'
  const disableBatchBtn = ref(true) // 是否禁用批量操作按钮，默认禁用
  const loading = ref(false) // 列表加载动画
  const listFieldSearch = ref({
    // 搜索条件
    page: 1,
    limit: 50,
    name: '',
  })
  const selectFieldIds = ref([]) // 列表选中的字段ID
  const networkEmpFieldDialog = ref(false) // 新增/修改弹窗
  const networkEmpFieldVo = ref({
    id: '',
    name: '',
    type: 1, // 字段类型：1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频，8-评分
    status: false, // 	字段状态：false-启用，true-禁用
    required: false, // 是否必填：false-不必填，true-必填,示例值(true)
    mobileShow: true,
    tip: '请输入',
    uploadQty: 1, // 	上传数量，最多可上传10张,示例值(10)
    uploadSize: 100, // 图片、附件、视频上传尺寸大小，单位：M,示例值(100)
    delContentIds: [], // 删除的单选/多选内容ID
    contents: [{ id: '', val: '' }],
  })

  const fieldDialogTitle = ref() // 新增/修改字段弹窗标题
  const fieldDialogLoading = ref(false) // 新增/修改字段弹窗加载动画
  const fieldTotal = ref() // 总数目
  const tableData = ref() //表格总数据
  const tableDom = ref() //表格dom
  const pagingtion = ref() // 分页Dom
  // 列表选项框选中事件
  const handleChange = (val: any[]) => {
    selectFieldIds.value = []
    val.forEach((item) => {
      selectFieldIds.value.push(item.id)
    })
  }

  // 清除列表选中列事件
  const clearTableSelection = () => {
    tableDom.value.clearSelection()
    selectFieldIds.value = []
  }

  // 初始化字段值
  const initField = () => {
    networkEmpFieldVo.value = {
      id: '',
      name: '',
      type: 1, // 字段类型：1-文本，2-多行文本，3-单选，4-多选，5-多图，6-附件，7-视频，8-评分
      status: false, // 	字段状态：false-启用，true-禁用
      required: false, // 是否必填：false-不必填，true-必填,示例值(true)
      mobileShow: true,
      tip: '请输入',
      uploadQty: 1, // 	上传数量，最多可上传10张,示例值(10)
      uploadSize: 100, // 图片、附件、视频上传尺寸大小，单位：M,示例值(100)
      delContentIds: [], // 删除的单选/多选内容ID
      contents: [{ id: '', val: '' }],
    }
  }

  // 打开添加字段弹窗
  const onOpenAddField = () => {
    networkEmpFieldDialog.value = true
    fieldDialogTitle.value = '添加服务人员字段'
    initField()
  }

  // 打开修改字段弹窗
  const onOpenEditField = async (obj: any) => {
    fieldDialogTitle.value = '编辑服务人员字段'
    fieldDialogLoading.value = true
    initField()
    await getNetworkEmpFieldDetail(obj.id).then((res) => {
      fieldDialogLoading.value = false
      networkEmpFieldVo.value = res.data.data.row
      networkEmpFieldDialog.value = true
    })
  }
  // 批量启用或禁用字段状态
  const updateBatchNetworkFieldStatus = (status: boolean) => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Warning),
      message: `是否 ${status ? '禁用' : '启用'} 选中的 ${selectFieldIds.value.length} 项? ${
        status ? '禁用后将不可被其他应用关联使用' : '启用后将被其他应用关联使用'
      }`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: `${status ? '确认禁用' : '确认启用'}`,
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = `${status ? '禁用' : '启用'}中...`
          setTimeout(() => {
            done()
            updateNetworkEmpFieldStatusApi(status)
            instance.confirmButtonLoading = false
          }, 100)
        } else {
          done()
        }
      },
    }).catch(() => {})
  }

  // 批量删除字段
  const onDelBatchField = () => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      icon: markRaw(Delete),
      message: `是否删除选中的 ${selectFieldIds.value.length} 项? 删除后将不可恢复`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '删除中...'
          setTimeout(() => {
            done()
            delNetworkEmpFieldApi(selectFieldIds.value)
            instance.confirmButtonLoading = false
          }, 100)
        } else {
          done()
        }
      },
    }).catch(() => {})
  }

  // 请求启用或禁用字段状态Api
  const updateNetworkEmpFieldStatusApi = (status: boolean) => {
    batchUpdateNetworkEmpFieldStatus(selectFieldIds.value, status).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求删除字段Api
  const delNetworkEmpFieldApi = async (arr) => {
    await delNetworkEmpField(arr).then((res) => {
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        networkEmpFieldDialog.value = false
        getList()
        clearTableSelection()
      }
    })
  }

  // 请求保存字段Api
  const saveApi = async (e) => {
    networkEmpFieldVo.value = e
    fieldDialogLoading.value = true
    await saveNetworkEmpField(networkEmpFieldVo.value).then((res) => {
      fieldDialogLoading.value = false
      ElMessage({
        message: res.data.message,
        type: res.data.success ? 'success' : 'error',
        duration: 2000,
      })
      if (res.data.success) {
        networkEmpFieldDialog.value = false
        getList()
      }
    })
  }

  // 请求字段列表Api
  const getList = async () => {
    loading.value = true
    listFieldSearch.value.page = pagingtion.value.current
    listFieldSearch.value.limit = pagingtion.value.size
    await getNetworkEmpList(listFieldSearch.value).then((res) => {
      loading.value = false
      tableData.value = res.data.data.rows
      fieldTotal.value = parseInt(res.data.data.total)
    })
  }

  // 监听列表选中对象值变化
  watch(
    () => selectFieldIds.value,
    () => {
      disableBatchBtn.value = true
      if (selectFieldIds.value.length > 0) {
        disableBatchBtn.value = false
      }
    },
  )

  // 返回方法
  defineExpose({ getList })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
